package com.gtenacg.cartoonservice.controller;

import com.gtenacg.cartoonservice.common.annotation.CheckToken;
import com.gtenacg.cartoonservice.common.Result;
import com.gtenacg.cartoonservice.pojo.model.Author;
import com.gtenacg.cartoonservice.service.AuthorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/author")
@RequiredArgsConstructor
public class AuthorController {

    private final AuthorService authorService;

    @GetMapping("/list")
    public Result<List<Author>> list() {
        log.info("获取作者列表");
        List<Author> list = authorService.list();
        return Result.success(list);
    }

    @GetMapping
    public Result<List<Author>> search(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String gender
    ) {
        log.info("获取作者列表 = name:{},gender:{}",name,gender);
        List<Author> list = authorService.search(name,gender);
        return Result.success(list);
    }

    @CheckToken
    @PostMapping
    public Result<Integer> insert(@RequestBody Author author) {
        log.info("新增作者信息: {}", author);
        Integer id = null;
        try {
            id = authorService.insert(author);
        } catch (DuplicateKeyException e) {
            log.info("异常：唯一约束，新增操作被拒绝！！！");
            return new Result<>(HttpStatus.CONFLICT.value(), "Duplicate_Key", null);
        }
        return Result.success(id);
    }

    @CheckToken
    @PutMapping
    public Result<Void> update(@RequestBody Author author) {
        log.info("修改作者信息: {}", author);
        authorService.update(author);
        return Result.success();
    }

    @CheckToken
    @DeleteMapping("/{ids}")
    public Result<Void> delete(@PathVariable List<Integer> ids) {
        log.info("删除作者信息: {}", ids);
        authorService.delete(ids);
        return Result.success();
    }

}
